package com.itestor.iptv.global.utils;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.Globals;

/**
 * 区域切换Interceptor.
 * @author TrueOrFalse.Yuan
 */
@SuppressWarnings("unused")
public class LocalChangeInterceptor implements MethodInterceptor {

	private static final String RP_LOCAL_DEFAULT = "local";
	private static final String STR_LOCAL_SPLIT = "_";

	private String requestParameterLocal = RP_LOCAL_DEFAULT;

	/**
	 * @param invocation 参数
	 * @return object
	 * @throws Throwable any exception
	 **/
	public Object invoke(MethodInvocation invocation) throws Throwable {
		HttpServletRequest request = (HttpServletRequest) invocation.getArguments()[2];
		HttpServletResponse response = (HttpServletResponse) invocation.getArguments()[3];

		String local = request.getParameter(requestParameterLocal);
		if(!StringUtils.isEmpty(local)){
			Locale currentLocale = null;
			if (StringUtils.contains(local, STR_LOCAL_SPLIT)) {
				currentLocale = new Locale(local.split(STR_LOCAL_SPLIT)[0], local.split(STR_LOCAL_SPLIT)[1]);
			} else {
				currentLocale = new Locale(local);
			}
			request.getSession().setAttribute(Globals.LOCALE_KEY, currentLocale);
		}
		return invocation.proceed();
	}

	public void setRequestParameterLocal(String requestParameterLocal) {
		this.requestParameterLocal = requestParameterLocal;
	}
}
